const Router = require('koa-router')
const path = require('path');
const fs = require('fs');
let PUBLIC_PATH = path.resolve(__dirname, '../caseImages/');
const qiniu = require('qiniu')
//文件上传
var formidable = require("formidable");
var form = new formidable.IncomingForm({
  encoding: 'utf-8',//上传编码
  uploadDir: PUBLIC_PATH,//上传目录，指的是服务器的路径，如果不存在将会报错。
  keepExtensions: true,//保留后缀
  maxFieldsSize: 2 * 1024 * 1024//byte//最大可上传大小
});
const router = new Router({
  prefix: '/admin'
})
const admin = require('../mysql/admin')
//createToken
const createToken = require('../token/createToken.js');
//checkToken
const checkToken = require('../token/checkToken.js');

//登录
router.post('/login', async (ctx) => {
  //拿到账号和密码
  let username = ctx.request.body.username;
  let password = ctx.request.body.password;

  let info = await admin.login(username, password);
  let doc = info[0]
  if (!doc) {
    ctx.body = {
      msg: '用户名不存在或者密码错误'
    }
  } else if (doc.C_PASSWORD === password || doc.C_USERNAME === username) {
    //生成一个新的token,并存到数据库
    let token = createToken(username);
    doc.token = token;
    /*await new Promise((resolve, reject) => {
        doc.save((err) => {
            if(err){
                reject(err);
            }
            resolve();
        });
    });*/
    ctx.status = 200;
    ctx.body = {
      msg: '登录成功！',
      username,
      token, //登录成功要创建一个新的token,应该存入数据库
    };
  }
})

//获取案例列表
router.post('/getCaseList', checkToken, async (ctx, next) => {
  let {page, size} = ctx.request.body
  let articleList = {}
  await admin.getCaseList(page, size)
    .then((res) => {
      articleList.rows = res
    })
    .catch(err => {
      ctx.throw(101, err)
    })
  await admin.getCaseListTotal()
    .then(res => {
      articleList.total = res[0]['COUNT(*)']
    })
  ctx.body = articleList
})
//获取指定案例
router.post('/getCase', checkToken, async (ctx, next) => {
  let {id} = ctx.request.body
  await admin.getCase(id)
    .then((res) => {
      ctx.body = res
    })
    .catch(err => {
      ctx.throw(101, err)
    })
})
//编辑案例
router.post('/upDateCase', async (ctx, next) => {
  let {title, parentId, imgUrl, caseDetial, id} = ctx.request.body
  await  admin.upDateCase(title, parentId, imgUrl, caseDetial, id)
    .then(() => {
      ctx.body = {
        code: 200,
        message: '修改成功'
      }
    })
    .catch(() => {
      ctx.body = {
        code: 99,
        message: '修改失败'
      }
    })
})
//上传案例
router.post('/addCase', async (ctx, next) => {
  let {title, parentId, imgUrl, caseDetial} = ctx.request.body
  await  admin.addCase(title, parentId, imgUrl, caseDetial)
    .then(() => {
      ctx.body = {
        code: 200,
        message: '上传成功'
      }
    })
    .catch(() => {
      ctx.body = {
        code: 99,
        message: '上传失败'
      }
    })
})
//发布文章
router.post('/postArticle', checkToken, async (ctx, next) => {
  let {title, typeName, time, isLove, description, imgUrl, html} = ctx.request.body
  await  admin.postArticle(title, typeName, time, isLove, description, imgUrl, html)
    .then(() => {
      ctx.body = {
        code: 200,
        message: '发表成功'
      }
    })
    .catch(() => {
      ctx.body = {
        code: 99,
        message: '发表失败'
      }
    })
})

//删除文章
router.post('/delateArticle', async (ctx, next) => {
  let {id} = ctx.request.body
  await  admin.delateArticle(id)
    .then(res => {
      ctx.body = {
        code: 200,
        message: res
      }
    })

})
//编辑文章
router.post('/upDateArticle', async (ctx, next) => {
  let {title, typeName, time, isLove, description, imgUrl, html, id} = ctx.request.body
  await  admin.upDateArticle(title, typeName, time, isLove, description, imgUrl, html, id)
    .then(() => {
      ctx.body = {
        code: 200,
        message: '修改成功'
      }
    })
    .catch(() => {
      ctx.body = {
        code: 99,
        message: '修改失败'
      }
    })
})

//文件上传

router.post('/upload', async (ctx, next) => {
  var allFile = [];
  form.on('progress', function (bytesReceived, bytesExpected) {//在控制台打印文件上传进度
    var progressInfo = {
      value: bytesReceived,
      total: bytesExpected
    };
    console.log('[progress]: ' + JSON.stringify(progressInfo));
    // ctx.res.write(JSON.stringify(progressInfo));
  })
    .on('file', function (filed, file) {
      allFile.push([filed, file]);//收集传过来的所有文件
    })
    .on('end', function () {
      ctx.res.end('上传成功！');
    })
    .on('error', function (err) {
      console.error('上传失败：', err.message);
      next(err);
    })
    .parse(ctx.req, function (err, fields, files) {
      if (err) {
        console.log(err);
      }
      // allFile.forEach(function (file, index) {
      //     // var fieldName = file[0];
      //     var types = file[1].name.split('.');
      //     // var date = new Date();
      //     // var ms = Date.parse(date);
      //     fs.renameSync(file[1].path, form.uploadDir + "/" + types[0] + "." + String(types[types.length - 1]));//重命名文件，默认的文件名是带有一串编码的，我们要把它还原为它原先的名字。
      // });
    });
})

router.post('/getToken',async (ctx,next)=>{
  var accessKey = '6mKfmytq5JDfTJXwNs32fsvKW1A8ABBG4CxNCI-8';
  var secretKey = '65EUyEBPB-SR0wCB3SM2y2zy8sGjjAS-78gv6S5c';
  var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
  var options = {
    scope:  'huangjianhui',
  };
  var putPolicy = new qiniu.rs.PutPolicy(options);
  var uploadToken=putPolicy.uploadToken(mac);
  ctx.body = {
    token:uploadToken
  }
})


module.exports = router